<template>
    <div class="dhzn_users">

        <div class="d_users-add">

            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="昵称">
                    <el-input v-model="formInline.nickname" placeholder="注册用户名" clearable></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input placeholder="用户注册手机号" v-model="formInline.phone" maxlength="11" clearable onkeyup="this.value=this.value.replace(/\D/g,'')">
                        <!-- <i slot="suffix" v-if="formInline.pwd !== ''"  @click="examine" class="iconfont icon-renleihuman90"></i> -->
                    </el-input>
                </el-form-item>
                <el-form-item label="会员">
                    <el-select v-model="formInline.level" placeholder="选中相应等级的会员" clearable>
                    <el-option label="1星会员" value="1"></el-option>
                    <el-option label="2星会员" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button type="danger" @click="subreset">重置</el-button>
                </el-form-item>
            </el-form>

        </div>

        <div class="d_users-list">

            <table class="d_u-l-table f14 tc" cellspacing="0" cellpadding="0" border="1">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>账户信息</th>
                        <th>所属上级</th>
                        <th>账号状态</th>
                        <th>下级用户数</th>
                        <th>店铺会员</th>
                        <th>入驻时间</th>
                        <th>所在城市</th>
                        <th>详细地址</th>
                        <th>操作</th>
                    </tr>
                </thead>

                <tbody>
                    <tr v-for="(item,key) in userlist" :key="key">
                        <td>{{item.id}}</td>
                        <td><span @click="dialoguserinfo = true">{{item.userid}}{{item.openid}}</span></td>
                        <td>{{item.topid}}</td>
                        <td>{{item.state}}</td>
                        <td>{{item.userNum}}</td>
                        <td>{{item.memberNum}}</td>
                        <td><span v-if="item.createTime !== null">{{item.createTime*1000 | formatDate}} {{item.createTime*1000 | formatDateBehind}}</span></td>
                        <td>{{item.city}}</td>
                        <td>{{item.address}}</td>
                        <td class="d_ult-td">
                            <el-button type="primary" @click="upuserdata(item,key)" class="f16">修改</el-button>
                            <el-button type="danger" @click="deletedata(item.id)" class="f16">删除</el-button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <el-dialog title="修改员工信息" :visible.sync="dialogFormVisible" :lock-scroll="false" top="20vh" width="450px">
								
                <p class="tc red">*灰色是原信息，填好修改信息后点击确定，信息自动更新</p>

                <el-form :model="upinput" label-width="80px" class="demo-ruleForm">
                    <el-form-item label="" v-for="(item,key) in upinput" :key="key">
                        <label slot="label">{{item.name}}</label>
                        <el-input class="dxm-ltbm-price" v-model="item.value" max="220px" :placeholder="item.text" clearable></el-input>
                    </el-form-item>
                    
                    <div class="d_ult-t-confirm mt20 tc">
                        <el-button type="primary" @click="refer" class="d_ult-tc-btn wh">确定</el-button>
                    </div>
                </el-form>
                <!-- <div class="d_ult-t-message mt20 df" v-for="(item,key) in upinput" :key="key">
                    <span :class="item.class">{{item.name}}</span>
                    <el-input class="dxm-ltbm-price" v-model="item.value" max="220px" :placeholder="item.text" clearable></el-input>
                </div> -->
            </el-dialog>

            <el-dialog  :visible.sync="dialoguserinfo" :lock-scroll="false" width="450px">
								
                <div>
                    <div class="tc"><img :src="item.imgeurl === '' ? 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2630270280,153221653&fm=26&gp=0.jpg' : (item.imageurl)" alt=""></div>
                </div>
                
            </el-dialog>

            <div class="d_u-l-t-block mt20">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5,10,15,20]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>

        </div>

    </div>
</template>

<script>
import axios from "../js/request.js"
import {formatDate} from '../js/time.js'
// var axios = require('axios')
export default {
    components: {},
    data() {
        return {
            token: '',                           //登录验证
            // 数据数组
            userlist: [],
            typestate: "password",
            formInline: {
                nickname: '',
                phone: '',
                level: ''
            },
            dialogFormVisible: false,           //弹出层的状态
            // 身份信息修改框的循环数组
            upinput:[
                {id: 0,name: "用户昵称",value: "",text:'',keyname:'nickname'},
                {id: 1,name: "用户密码",value: "",text:'',keyname:'password'},
                {id: 2,name: "用户余额",value: "",text:'',keyname:'balance'},
                {id: 3,name: "手机号码",value: "",text:'',keyname:'phone'},
                // {id: 4,name: "",value: "",text:''},
            ],
            dialoguserinfo: false,
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						    //总条数
        };
    },
    filters: {
        formatDate(time) {							 //日期(年月日)
            var date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd');   //年月日 格式自己定义   'yyyy : MM : dd'  例 2018年12月5日的格式
        },
        formatDateBehind(time) {					 //时间(时分秒)
            var date = new Date(time);
            return formatDate(date, 'hh:mm:ss');     //时间点 例 21点12分12秒的格式
        },
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            const that = this;
            that.pagesize = val
            if(that.formInline.user !== '' || that.formInline.phone !== '' || that.formInline.vip !== ''){
                that.onSubmit()
            }else{
                that.userdata()
            }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            const that = this;
            that.currentPage = val;
            if(that.formInline.user !== '' || that.formInline.phone !== '' || that.formInline.vip !== ''){
                that.onSubmit()
            }else{
                that.userdata()
            }
        },

        // 表单提交的函数
        onSubmit() {
            const that = this;
            if(that.formInline.user !== '' || that.formInline.phone !== '' || that.formInline.vip !== ''){
                let data = {
                    current:that.currentPage, 
                    size:that.pagesize,
                }
                let axios = require('axios');
                for (var p in that.formInline){
                    if(that.formInline[p] !== ''){
                        data[p] = that.formInline[p]
                    }
                }
                let updata = JSON.stringify(data)
                axios({
                    method: 'post',
                    url: '/api/user/list',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                })
                .then( resp=> {
                    // console.log(resp)
                    that.userlist = resp.data.data;
                    that.total = resp.data.code;
                    if(that.userlist === undefined){
                        console.log("token过期")
                        sessionStorage.removeItem("token")
                        location.reload()
                    }else{return}
                })
                .catch( err=> {console.log(err)})
            }else{
                that.$message.error("至少需要一个查询条件")
            }
        },

        // 查询框重置
        subreset(){
            const that = this;
            that.formInline.user = '';
            that.formInline.phone = '';
            that.formInline.vip = '';
        },

        // 列表数据
        userdata(){
            let that = this;
            console.log('123')
            // let axios = require('axios');
            // let data = {current:that.currentPage, size:that.pagesize};
            // let updata = JSON.stringify(data)
            // axios.requset("/user/list","post",{current:that.currentPage,size:that.pagesize}).then(resp=>{
            axios.request("/user/list","post",{current:that.currentPage,size:that.pagesize}).then(resp=>{
            // axios({
            //     method: 'post',
            //     url: '/api/user/list',
            //     headers: {
            //         'Content-Type': 'application/json',
            //         'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
            //     },
            //     data: updata
            // })
            // .then( resp=> {
                console.log(resp)
                that.userlist = resp.data.data
                that.total = resp.data.code
            }).catch( err=> {console.log(err)})
        },

        // 数据更新（修改用户数据）
        upuserdata(arr,key){
            const that = this;
            that.dialogFormVisible = true
            that.zeroof = arr
            // 把函数携带的值带入到动态绑定的变量中，更新数据时使用
            for(var t=0;t<that.upinput.length;t++){
                let keyname =  that.upinput[t].keyname
                that.upinput[t].text = that.zeroof[keyname];
            }
            that.upinput[3].id = that.zeroof.id;
            that.upinput[3].openid = that.zeroof.openid;
            that.upinput[3].key = key
        },
        refer(){
            const that = this;
            let axios = require('axios')

            that.$confirm('用户信息修改后无法找回，请再次确认', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            center: 'true'
            })
            .then(() => {

                // 修改员工信息的请求
                let data = {
                    id: that.upinput[3].id,
                    openid: that.upinput[3].openid
                }
                // 传值的判断，空川默认值，有值传新值
                for(var q=0;q<that.upinput.length;q++){
                    if(that.upinput[q].value !== ''){
                        data[that.upinput[q].keyname] = that.upinput[q].value
                    }else{
                        data[that.upinput[q].keyname] = that.upinput[q].text
                    }
                }
                let updata = JSON.stringify(data)
                console.log(updata)
                axios({
                    method: 'post',
                    url: "/api/user/update",
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                    },
                    data: updata
                })
                .then( resp=> {
                    // console.log(resp)
                    let key = that.upinput[3].key
                    that.userlist[key].nickname = data.nickname;
                    that.userlist[key].password = data.password;
                    that.userlist[key].balance = data.balance;
                    that.userlist[key].phone = data.phone
                    that.dialogFormVisible = false;
                    if(that.userlist === undefined){
                        // console.log("token过期")
                        sessionStorage.removeItem("token")
                        location.reload()
                    }else{return}
                })
                .catch( err=> {console.log(err)})

            that.$message({
                    type: 'success',
                    message: '修改成功!'
                });
            })

            .catch(() => {
                that.$message({
                    type: 'info',
                    message: '已取消修改'
                });          
            });
        },

        // 用户删除
        deletedata(id){
            const that = this;
            let data = {id: id};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/user/delete',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                if(that.userlist === undefined){
                    // console.log("token过期")
                    sessionStorage.removeItem("token")
                    location.reload()
                }else{return}
            })
            .catch( err=> {console.log(err)})
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.userdata()
			}).catch( err=> {})
        }
    },
    created() {},
    mounted() {
        const that = this;
        that.newtoken()
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
    .dhzn_users{
        height: calc(100% - 56px);
        box-sizing: border-box;
    }
    /* 添加用户 */
    .demo-form-inline{
        display: flex;
        justify-content: space-between;
        width: auto;
        margin-bottom: 20px;
        padding: 0 15px;
        background-color: #ffffff;
        border-radius: 5px;
    }
    .el-form-item{
        margin: 20px 0;
    }
    /* 数据加分页 */
    .d_users-list{
        height: calc(100% - 100px);
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        background-color: #ffffff;
    }

    /* 数据列表 */
    .d_u-l-table{
        width: 100%;
        color: #666666;
        border-bottom: 1px solid #e0e0e0;
        border-left: 1px solid  #e0e0e0;
        border-collapse: collapse;
    }
    .d_u-l-table thead tr{
        background-color: #F2F2F2;
    }
    .d_u-l-table tbody tr:hover{
        background-color: #F2F2F2;
    }
    .d_u-l-table th, .d_u-l-table td{
        min-height: 50px;
        padding: 10px;
        border-top: 1px solid #e0e0e0;
        border-right: 1px solid #e0e0e0;
    }
    /* 图片大小的 */
    .d_u-l-table tr td img{
        max-width: 120px;
        max-height: 80px;
    }
    /* el-button默认样式修改 */
    .el-button+.el-button{
        margin: 0;
    }
    .d_u-l-table tr td .el-button{
        padding: 9px 13px;
    }
    /* 左边的图片预览效果 */
    /* .d_gld-t-popover img{
        max-width: 500px;
        max-height: 500px;
    } */



    /* 分页样式 */
    .d_u-l-t-block{
        text-align: center;
        margin-top: 20px;
    }
</style>